from django.shortcuts import render,redirect

# Create your views here.

from db import models
from public_mode import views
import  os
import time
import datetime
import requests
import subprocess
def fileadminlist(request):

    user_name = request.session.get("user_key")
    user_project_list_tmp = views.user_project(user_name)
    info = {"my_name": user_name}
    user_project_list = models.ProJect.objects.filter(id__in=user_project_list_tmp).values()
    info["user_project_list"] = user_project_list
    if request.method == "GET":
        file_list = models.fileadmin.objects.filter(file_project__id__in=user_project_list_tmp).values("file_name","file_url","file_md5","file_uptime","file_owner__user_name","file_project__p_name").order_by('-id')[0:100]
        info["file_list"] = file_list
        return  render(request,'fileadminlist.html',info)
    else:
        project_id = request.POST.get("project_id")
        project_name = models.ProJect.objects.filter(id=project_id).values()[0]["p_name"]
        s_time_start =  request.POST.get("s_time_start")
        s_time_end = request.POST.get("s_time_end")
        now_time = datetime.datetime.now().strftime("%Y-%m-%d")
        if s_time_start =="" and s_time_end=="":
            file_list = models.fileadmin.objects.filter(file_project__id=project_id).values("file_name", "file_url",
                                                                                            "file_md5", "file_uptime",
                                                                                            "file_owner__user_name",
                                                                                            "file_project__p_name").order_by(
                '-id')[0:100]

        elif s_time_start !="" and s_time_end=="":
            s_time_end = now_time
            file_list = models.fileadmin.objects.filter(file_project__id=project_id,file_uptime__gte=s_time_start).values("file_name", "file_url",
                                                                                            "file_md5", "file_uptime",
                                                                                            "file_owner__user_name",
                                                                                            "file_project__p_name").order_by(
                '-id')[0:100]
        elif s_time_start =="" and s_time_end !="":
            file_list = models.fileadmin.objects.filter(file_project__id=project_id,
                                                        file_uptime__lte=s_time_end).values("file_name", "file_url",
                                                                                            "file_md5", "file_uptime",
                                                                                            "file_owner__user_name",
                                                                                            "file_project__p_name").order_by(
                '-id')[0:100]

        else:
            file_list = models.fileadmin.objects.filter(file_project__id=project_id, file_uptime__gte=s_time_start,
                                                        file_uptime__lte=s_time_end).values("file_name", "file_url",
                                                                                            "file_md5", "file_uptime",
                                                                                            "file_owner__user_name",
                                                                                            "file_project__p_name").order_by(
                '-id')[0:100]


            # print(file_list)
        info["file_list"] = file_list
        info["project_name"] = project_name
        info["project_id"] = project_id
        return render(request, 'fileadminlist.html', info)



def fileadminupload(request):
    user_name = request.session.get("user_key")
    user_project_list_tmp = views.user_project(user_name)
    info = {"my_name": user_name}
    user_project_list = models.ProJect.objects.filter(id__in=user_project_list_tmp).values()
    info["user_project_list"] = user_project_list
    if request.method == "GET":
      return render(request,"fileadminup.html",info)
    else:
        file_md5 = request.POST.get("file_md5").lower()
        project_id = request.POST.get("project_id")
        file_uptime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime());
        upload_file = request.FILES.get("upload_file")
        dir_time=time.strftime("%Y%m%d",time.localtime());
        dir_two=request.POST.get("dir_two")
        p_name_alias = models.ProJect.objects.filter(id=project_id).values("p_name_alias")[0]["p_name_alias"]
        cdn_status = request.POST.get("cdn_status")
        if cdn_status == "0":
            if p_name_alias == "None":
                if dir_two == "":
                    file_url='/static/fileadmin/%s/%s/%s' %(project_id,dir_time,upload_file.name)
                    dir_path = 'static/fileadmin/%s/%s' % (project_id, dir_time)
                else:
                    file_url = '/static/fileadmin/%s/%s/%s/%s' % (project_id, dir_time,dir_two,upload_file.name)
                    dir_path = 'static/fileadmin/%s/%s/%s' % (project_id, dir_time,dir_two)
            else:
                if dir_two == "":
                    file_url='/static/fileadmin/%s/%s/%s' %(p_name_alias,dir_time,upload_file.name)
                    dir_path = 'static/fileadmin/%s/%s' % (p_name_alias, dir_time)
                else:
                    file_url = '/static/fileadmin/%s/%s/%s/%s' % (p_name_alias, dir_time,dir_two,upload_file.name)
                    dir_path = 'static/fileadmin/%s/%s/%s' % (p_name_alias, dir_time,dir_two)
        else:
            cdn_domain = models.cdnconfig.objects.values()[0]["cdn_domain"]
            if p_name_alias == "None":
                if dir_two == "":
                    file_url='%s/%s' %(cdn_domain,upload_file.name)
                    dir_path = 'static/fileadmin/%s' % (project_id)
                else:
                    file_url = '%s/%s/%s' % (cdn_domain,dir_two,upload_file.name)
                    dir_path = 'static/fileadmin/%s/%s' % (project_id,dir_two)
            else:
                if dir_two == "":
                    file_url='%s/%s' %(cdn_domain,upload_file.name)
                    dir_path = 'static/fileadmin/%s' % (p_name_alias)
                else:
                    file_url = '%s/%s/%s' % (cdn_domain,dir_two,upload_file.name)
                    dir_path = 'static/fileadmin/%s/%s' % (p_name_alias,dir_two)



        if os.path.exists(dir_path):
            pass
        else:
            os.makedirs(dir_path)



        f = open(os.path.join(dir_path,upload_file.name),'wb')
        for chunk in upload_file.chunks():
            f.write(chunk)
        f.close()
        file_status = models.fileadmin.objects.filter(file_name=upload_file.name,file_url=file_url).count()
        if file_status == 0:
            models.fileadmin.objects.create(file_name=upload_file.name,file_url=file_url,file_md5=file_md5,file_uptime=file_uptime)
        else:
            models.fileadmin.objects.filter(file_name=upload_file.name,file_url=file_url).update(file_name=upload_file.name, file_url=file_url, file_md5=file_md5,
                                            file_uptime=file_uptime)

        file_id = models.fileadmin.objects.filter(file_name=upload_file.name,file_url=file_url).values()[0]["id"]
        user_id = models.user_info.objects.filter(user_name=user_name).values()[0]["id"]
        obj = models.fileadmin.objects.get(id=file_id)
        obj.file_owner.set([user_id])
        obj.file_project.set([project_id])

        if cdn_status == "1":
            cdn_config_status = models.cdnconfig.objects.values().count()
            if cdn_config_status == 0:
                pass
            else:
                cdn_config_info = models.cdnconfig.objects.values()[0]
                home_dir = cdn_config_info["home_dir"]
                cdn_id = cdn_config_info["cdn_id"]
                source_ip = cdn_config_info["cdn_source_ip"]
                dist_dir = cdn_config_info["dist_dir"]
                file_source_path = home_dir + "/" +  dir_path
                #同步文件到cdn源服务器
                cmd="rsync -avz %s %s:%s" %(file_source_path,source_ip,dist_dir)
                result_tmp = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)





                # 刷新cdn
                urls = file_url
                cdn_info = models.CdnAdmin.objects.filter(id=cdn_id).values("cdn_type__cdnalias","secretId", "secretKey")[0]
                if cdn_info["cdn_type__cdnalias"] == "tencent":
                    cmd = "python QcloudCdnTools_V2.py RefreshCdnUrl -u %s -p %s --urls %s" % (
                    cdn_info["secretId"], cdn_info["secretKey"], urls)

                    result_tmp = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
                    result = result_tmp.stdout.read()
                elif cdn_info["cdn_type__cdnalias"] == "dnion":
                    r_parameter = {"username": cdn_info["secretId"], "password": cdn_info["secretKey"], "url": urls,
                                   "type": 1}
                    result_tmp = requests.get("http://push.dnion.com/cdnUrlPush.do", params=r_parameter)
                    result = result_tmp.text
                elif cdn_info["cdn_type__cdnalias"] == "qingcdn":
                    headers = {'content-type': 'application/json'}
                    r_parameter = {"urls": [urls],
                                   "type": "url"}
                    result_tmp = requests.post(
                        "https://api.qingcdn.com/v2/cache/refresh?token=%s" % (cdn_info["secretKey"]), json=r_parameter,
                        headers=headers)
                    result = result_tmp.text
                else:
                    pass

        else:
            pass


        return redirect("/fileadmin/list/")

def fileadmindel(request):
    if request.method == "GET":
        file_url =  request.GET.get("file_url")
        if file_url != None:
            if "http" in file_url:
                pass
            else:
                models.fileadmin.objects.filter(file_url=file_url).delete()
        else:
            pass
    else:
        pass
    return redirect("/fileadmin/list/")